package ioServer;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class WebServer {
    private ServerSocket serverSocket;
    List<Socket> socketList = new ArrayList<>();
    ExecutorService executorService = Executors.newFixedThreadPool(2);
    public void run(int port) throws IOException {
        executorService.execute(()->{
            try {
                serverSocket = new ServerSocket(port);
                System.out.println("服务已启动 端口:" + port);
            while (true) {
                Socket socket = serverSocket.accept();
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream(), "GBK"));
                String line = null;

                char[] buffer = new char[1024];
                int length = 0;
                StringBuilder str = new StringBuilder();
                while (true) {
                    length = bufferedReader.read(buffer);
                    str.append(buffer);
                    //表示数据以读完
                    if (length <= 0 || length < 1024) {
                        break;
                    }
                }
                System.out.println(str.toString());
                socketList.add(socket);
            }

            }catch (Exception e){
                e.printStackTrace();
                System.out.println("异常");
            }
        });

        while (true){
            Scanner scanner = new Scanner(System.in);
            String x = scanner.nextLine();
            socketList.forEach(item->{
                try {
                    BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(item.getOutputStream(), "GBK"));
                    writer.write(x +"HTTP/1.1 200OJBK\r\n");
                    writer.write("ContentType: text/html;charset=UTF-8\r\n");
                    writer.write("\r\n");
                    writer.write("hello, 摸摸大!");
                    writer.flush();
//                socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            });
            System.out.println(x);
        }


    }
}
